const { ipcRenderer } = require('electron')
const fs = require('fs')

ipcRenderer.on('BrowseResult', (event, arg) => {
  switch (arg.type) {
    case 'File':
      ShowName('filename', arg.path[0])
      break
    case 'Folder':
      ShowName('foldername', arg.path[0])
      break
    default:
      break
  }
})

function BrowseFile() {
  ipcRenderer.send('Browse', 'File')
  return false
}

function BrowseFolder() {
  ipcRenderer.send('Browse', 'Folder')
  return false
}

function ShowName(id, name) {
  let ctrl = document.getElementById(id)
  ctrl.setAttribute("value", name)
}

const magic = Buffer.from([0x54, 0x45, 0x4C, 0x09, 0x58, 0x33, 0x69, 0x00])
let fileData

function Parse() {
  let filename = document.getElementById('filename').getAttribute('value')
  console.log(filename)
  fs.access(filename, (err) => {
    if (err) {
      alert(`"${filename}" doesnot exist`)
      return
    }

    fs.readFile(filename, (err, data) => {
      if (err) {
        alert(`Failed to read "${filename}"`)
        return
      }

      let index = data.indexOf(magic)
      if (index < 0) {
        alert(`"${filename}" is not a valid binary file`)
        return
      }

      let table = document.getElementById('itemTable')
      table.appendChild(CreateTableHead())

      let offset = index + magic.length + 4
      let recordCount = data.readUInt16BE(offset)
      offset += 2
      for (let i = 0; i < recordCount; ++i) {
        table.appendChild(CreateTableRow(ReadRecord(data, offset)))
        offset += 11
      }
    })

  })
  return false
}

function ReadRecord(buf, offset) {
  return {
    id: buf.readUInt16BE(offset),
    start: buf.readUInt32BE(offset + 2),
    length: buf.readUInt32BE(offset + 6),
    flag: buf.readUInt8(offset + 10)
  }
}

function CreateTableHead() {
  let head = document.createElement('tr')

  for (name of ['ID', 'Start', 'Length', 'Flag', 'Action']) {
    let text = document.createTextNode(name)
    let th = document.createElement('th')
    th.appendChild(text)
    head.appendChild(th)
  }

  return head
}

function CreateActionExport(name, id, callback=null) {
  let act = document.createElement('input')
  act.setAttribute('type', 'button')
  act.setAttribute('id', id)
  act.setAttribute('value', name)
  return act
}

function CreateTableRow(rec) {
  let row = document.createElement('tr')
  for (name of ['id', 'start', 'length', 'flag']) {
    let text = document.createTextNode(rec[name].toString(16))
    let td = document.createElement('td')
    td.appendChild(text)
    row.appendChild(td)
  }

  let act = document.createElement('td')
  act.appendChild(CreateActionExport('Export', 'EXPORT-'+rec.id.toString(16)))
  row.appendChild(act)

  return row
}
